exports.handler = function(sid, query, callback) {
        
    var start = (new Date(query.start + " 00:00:00")).getStamp();
    var end = (new Date(query.end + " 00:00:00")).getStamp();
    var condition = {'time':{'$gte':start, '$lt':end}};

    var db = gServers.getGameDB(sid);
    if (!db) {
       callback('db eror'); return;
    }
    
    var uidMap = {}; //{uid:openid}
    async.series([
        function(cb) {
            if (!query.openids) {
                cb(); return;
            }

            var cursor = db.collection('plat').find({'_id':{'$in':query.openids}}, {});
            cursor.each(function(err, item) {
                if (err || cursor.isClosed()) {
                    cb(err); return;
                }
                
                if (item.uid) {
                    uidMap[item.uid] = item._id;
                }
                if (item.uids) {
                    item.uids.forEach(function(uid) {
                        uidMap[uid] = item._id;
                    });
                }
            });
        },
        function(cb) {
            if (query.openids) {
                var uids = Object.keys(uidMap);
                if (uids.length == 0) {
                    cb(); return;
                }
                
                for (var i = 0; i < uids.length; ++i) {
                    uids[i] = +uids[i];
                }

                condition['uid'] = {'$in':uids};
            }

            if (query.uids) {
                condition['uid'] = {'$in':query.uids};
            }

            if (query.uid) {
                condition['uid'] = +query.uid;
            }
            
            var cursor = db.collection('cash').find(condition, {});
            cursor.each(function(err, item) {
                if (err || cursor.isClosed()) {
                    cb(err); return;
                }
                
                var obj = [uidMap[item.uid], sid, item.uid, item.mod, item.act, item.num, item.remain,
                    Date.createFromStamp(item.time).stdFormatedString(), item.level];
                console.log(obj.join('\t')); 
            });
        },
    ], function(err) {
        callback(err);
    });
}

exports.checkQuery = function(query) {
    var start = query.start;
    var end = query.end;
    if (!start || !end || start.length != 10 || end.length != 10) {
        return false;
    }

    return true;
}

exports.help = function() {
    return [
        "start=yyyy-MM-dd end=yyyy-MM-dd [openids=file] [uids=file] [uid=0]",
        "导出元宝明细,开始时间>=start,结束时间<end",
    ];
}

exports.getTitle = function(query) {
    var title = ['openid', 'sid', 'uid', 'mod', 'act', '数量', '剩余数量', '时间', '角色等级'];
    console.log(title.join('\t'));
}
